//
//  NativeUnicodeChannel.m
//  kq_flutter_widgets
//
//  Created by wtb on 2023/4/17.
//

#import "NativeUnicodeChannel.h"
#import "KqTool.h"

@implementation NativeUnicodeChannel
+(void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar{
    FlutterMethodChannel *channel = [FlutterMethodChannel methodChannelWithName:@"flutter.keqiang.com/fileUnicode" binaryMessenger:[registrar messenger]];
    NativeUnicodeChannel *unicode = [[NativeUnicodeChannel alloc] init];
    [registrar addMethodCallDelegate:unicode channel:channel];
}

-(void)handleMethodCall:(FlutterMethodCall *)call result:(FlutterResult)result{
    if ([@"fileUnicode" isEqualToString:call.method]) {
        NSString *path = call.arguments[@"path"];
        NSString *fileType = call.arguments[@"fileType"];
        if (path) {
            NSString *component = @"gf_file_cloud.txt";
            if ([fileType isEqualToString:@"html"]) {
                component = @"gf_file_web.html";
            }
            NSString *newPath = [KqTool getTmpImagePath:component folderName:@"kq_file"];
            
            NSString *contents = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
            
            //如果不是，则进行GBK编码
            if(!contents){
                contents = [NSString stringWithContentsOfFile:path encoding:0x80000632 error:nil];
            }
            //还不行就用GB18030编码再解码一次
            if (!contents) {
                contents = [NSString stringWithContentsOfFile:path encoding:0x80000631 error:nil];
            }
            if (contents) {
                contents = [contents stringByReplacingOccurrencesOfString:@"\n" withString:@"<br/>"];//替换换行符为HTML换行符
            }
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            if (contents) {
                //编码成功
                [dic setValue:@1 forKey:@"code"];
                [dic setValue:contents forKey:@"data"];
            }else{
                //编码失败
                [dic setValue:@0 forKey:@"code"];
                [dic setValue:@"编码失败" forKey:@"msg"];
            }
            result(dic);
        }
    }
}
@end
